<script setup>
import CommodityCard from "@/components/scenic-card/ScenicCard.vue"
import HotelCart from "@/components/hotel-card/HotelCart.vue"
import HotPotCart from "@/components/Hot-Pot-cart/HotPotCart.vue"
import {ref, watch, defineProps, reactive} from 'vue'
import {useRoute} from "vue-router"
import api from "@/api/index.js"
import { userStore } from '@/stores/user.js'
import { getToken } from '@/utils/user.js'
import { useKeepalive } from "@/hooks/useKeepalive.js"

const user = userStore()
const route = useRoute()
const searchKey = ref(route.params.searchKey)
const none = ref(false)

const props = defineProps({
  propSearchKey: String,
})

const needSaveRoute = ['scenicDetail', 'hotelDetail']
const { scrollYEle } = useKeepalive(needSaveRoute, 'SearchResult')

watch(() => props.propSearchKey, () => {
  searchKey.value = props.propSearchKey
  params.content = props.propSearchKey
  onRefresh()
})

const params = reactive({
  content: searchKey.value,
  pageNum: 1,
  pageSize: 10,
  queryHistoryFlag: '1',
  latitude: user.position?.coords?.longitude,
  longitude: user.position?.coords?.latitude
})
const list = ref([])
const totalCount = ref(0)
const loading = ref(false)
const error = ref(false)
const finished = ref(false)
const ordinaryFinished = ref(false)
// getSearchList
const onLoad = () => {
  if (!getToken()) {
    setHistoryList(params.content)
  }
  if (!ordinaryFinished.value) {
    _getScenicSpotsList()
  } else {
    _getSearchPandaScenicList()
  }
}

const _getScenicSpotsList = () => {
  api.getSearch(params).then((res) => {
    list.value = [...list.value, ...res.data.list]
    totalCount.value = res.data.totalCount
    params.pageNum += 1
    if (!res.data.totalCount) {
      none.value = true
    } else {
      none.value = false
    }
    if (list.value.length >= res.data.totalCount) {
      // if (getToken()) {
      //   _getSearchPandaScenicList()
      // } else {
      //   finished.value = true
      // }
      // ordinaryFinished.value = true
      finished.value = true
    } else {
      finished.value = false
    }
  }).catch(() => {
    error.value = true
  }).finally(() => {
    loading.value = false
    refreshing.value = false
  })
}

const pandaParams = {
  keyWord: params.content,
  goodsType: 0,
  pageNum: 1,
  pageSize: 9999
}
const _getSearchPandaScenicList = () => {
  api.getSearchPandaScenicList(pandaParams).then((res) => {
    list.value = [...list.value, ...res.data]
    pandaParams.pageNum += 1
    if (!res.data.totalCount) {
      none.value = true
    } else {
      none.value = false
    }
    finished.value = list.value.length >= res.data.totalCount;
  }).catch(() => {
    error.value = true
  }).finally(() => {
    loading.value = false
    refreshing.value = false
  })
}

const refreshing = ref(false)
const onRefresh = () => {
  list.value = []
  params.pageNum = 1
  onLoad()
}


const setHistoryList = (key) => {
  let historyList = []
  if (localStorage.getItem('historyList')) {
    historyList = JSON.parse(localStorage.getItem('historyList'))
  }
  const set = new Set([key, ...historyList])
  const list = Array.from(set)
  localStorage.setItem('historyList', JSON.stringify(list))
  // localStorage.setItem()
}

</script>

<template>
  <div class="result_list" ref="scrollYEle">
    <template v-if="!none">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          v-model:error="error"
          :finished="finished"
          finished-text="没有更多了"
          error-text="请求失败，点击重新加载"
          @load="onLoad"
        >
          <template v-for="(item, index) in list" :key="index">
            <CommodityCard v-if="item.kindId === '0'" class="list" :data="item" :keywords="[searchKey]"/>
            <HotelCart v-else-if="item.kindId === '2'" class="list" :data="item" :keywords="[searchKey]"/>
            <HotPotCart v-else-if="item.kindId === '3'" class="list" :data="item" :keywords="[searchKey]"/>
          </template>
        </van-list>
      </van-pull-refresh>
    </template>
    <template v-else>
      <div class="none">
        <img class="none_img" src="@/assets/images/index/none1.png" alt="">
        <span>暂无结果，换个词试试吧</span>
      </div>
    </template>
  </div>
</template>

<style scoped lang="scss">
.result_list{
  flex: 1;
  overflow-y: scroll;
  padding-bottom: 1.6rem;
  background: #F9F8F3;
  .list{
    margin: 1.5rem;
  }
  .none{
    display: flex;
    flex-direction: column;
    align-items: center;
    .none_img{
      width: 6rem;
      margin: 14.4rem 0 1rem 0;
    }
    span{
      font-size: 1.4rem;
      color: #666666;
    }
  }
}
</style>